package com.atguigu.gmall.product.controller;


import com.atguigu.gmall.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Api(tags = "分布式文件系统，文件上传")
@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    @Value("${fileServer.url}")
    private String fileServerUrl;

    @ApiOperation(value = "文件上传")
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file){
        String configFile = this.getClass().getResource("/tracker.conf").getFile();
        String path = "";
        if (configFile != null){
            try {
                ClientGlobal.init(configFile);//文件上传客户端
                TrackerClient trackerClient = new TrackerClient();
                TrackerServer trackerServer = trackerClient.getConnection();//获取trackerServer文件上传连接
                StorageClient1 storageClient1 = new StorageClient1(trackerServer,null);
                String extName = FilenameUtils.getExtension(file.getOriginalFilename());
                path = storageClient1.upload_appender_file1(file.getBytes(), extName, null);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.ok(fileServerUrl+path);
    }

}
